
/* layui插件封装 */

// pageType:TreeList/List/    分别为 带树的列表/普通列表
//          为TreeList-需要传 treeObj 
// useXmSelect:true/false
//        为true- 传targetids,targetimethods,创建targetidsChildren
//switchList:[{},{}]
//        用于生成开关
//
//


layui.define([
    'form',
    'table',
    'layer',
    'laypage',
    'layedit',
    'util',
    'element'
], function (exports) {
    'use strict';
    var $ = layui.$,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        util = layui.util,
        layedit = layui.layedit,
        element = layui.element,
        laypage = layui.laypage;

    var obj = {
        $: $,
        table: table,
        form: form,
        layer: layer,
        util: util,
        layedit: layedit,
        laypage: laypage,
        element: element,
        option: {
            primaryKay: null,
            pageType: '',
            tableId:'GvData',
            treePrimaryKey: null,
            useXmSelect: false,
            targetids: null,
            targetimethods: null,
            targetList: null,
            targetData: null,
            count: 0,
            switchList: null,
            useelement: false,
            Xmheight: "auto",
            btnSearch:"btnSearch"
        },
        RenderPage: function (option) {
            if (!obj.option.pageType) {
                layer.msg('页面类型未设置!', {
                    icon: 2
                });
                return;
            }

            obj.funSearch(); //搜索


            if (obj.option.switchList != null) {
                obj.funSwitch(); //开关
            }





        },
        funDtree: function (dtreeOption) {
            var option = {
                View: null,
                dtreePrimaryKey: null,
                tableID:null
            };
            option = $.extend({}, option, dtreeOption);
            if (option.View) {
                option.View.s = function (nodeId) {
                    var id = this.aNodes[nodeId].id;

                    var table = layui.table;
                    var field = null;
                    field = {};
                    field[option.dtreePrimaryKey] = id;

                    field['page'] = 1;

                    if (id == 0) {
                        field = null;
                    }

                    layui.use('table', function () {
                        //执行重载
                        table.reload(option.tableID, {
                            where: field,
                            text: "没有查找到数据",
                            page: {
                                curr: 1 //重新从第 1 页开始
                            },
                            done: function (res) {
                                if (res.count == 0) {
                                    //执行搜索后，不管是没有数据或者程序错误都执行该方法
                                    document.documentElement.querySelectorAll(".layui-table-body .layui-none")[0].innerHTML = res.msg;
                                }
                            }
                        });

                    });
                }

            }








        },
        funToolbar: function (toolOption) {
            var option = {
                TabelID: "GvData",
                seleAll: 0,
                active: null
            };
            option = $.extend({}, option, toolOption);

            //表格头部工具条监听，toolbar固定   GvData对应table的lay-filter="GvData"
            table.on('toolbar(' + option.TabelID + ')', function (toolbarObj) {
                var event = toolbarObj.event; //lay-event 对应的事件
                var checkrow = table.checkStatus(option.TabelID); //选中的表格数据arr 两个属性 data,isAll
                var checkdata = checkrow.data;

                if ("btn" === event.substring(0, 3)) {
                    option.active[event](checkdata);
                }
            });

            //全选
            if (option.seleAll == 1) {
                //筛选列添加全选，反选
                table.on('toolbar()', function (toolbarObj) {
                    var config = toolbarObj.config;
                    var btnElem = $(this);
                    var tableId = config.id;
                    var tableView = config.elem.next();
                    switch (toolbarObj.event) {
                        case 'LAYTABLE_COLS':
                            // 给筛选列添加全选还有反选的功能
                            var panelElem = btnElem.find('.layui-table-tool-panel');
                            var checkboxElem = panelElem.find('[lay-filter="LAY_TABLE_TOOL_COLS"]');
                            var checkboxCheckedElem = panelElem.find('[lay-filter="LAY_TABLE_TOOL_COLS"]:checked');
                            $('<li class="layui-form" lay-filter="LAY_TABLE_TOOL_COLS_FORM">' +
                                    '<input type="checkbox" lay-skin="primary" lay-filter="LAY_TABLE_TOOL_COLS_ALL" ' +
                                    ((checkboxElem.length === checkboxCheckedElem.length) ? 'checked' : '') + ' title="全选">')
                                .insertBefore(panelElem.find('li').first())
                                .on('click', '.LAY_TABLE_TOOL_COLS_Invert_Selection', function (event) {
                                    layui.stope(event);
                                    // 反选逻辑
                                    panelElem.find('[lay-filter="LAY_TABLE_TOOL_COLS"]+').click();
                                });
                            form.render('checkbox', 'LAY_TABLE_TOOL_COLS_FORM');
                            break;
                    }
                });

                // 监听筛选列panel中的全选
                form.on('checkbox(LAY_TABLE_TOOL_COLS_ALL)', function (obj) {
                    $(obj.elem).closest('ul')
                        .find('[lay-filter="LAY_TABLE_TOOL_COLS"]' + (obj.elem.checked ? ':not(:checked)' : ':checked') + '+').click();
                });

                // 监听筛选列panel中的单个记录的change
                $(document).on('change', 'input[lay-filter="LAY_TABLE_TOOL_COLS"]', function (event) {
                    var elemCurr = $(this);
                    // 筛选列单个点击的时候同步全选的状态
                    $('input[lay-filter="LAY_TABLE_TOOL_COLS_ALL"]')
                        .prop('checked',
                            elemCurr.prop('checked') ? (!$('input[lay-filter="LAY_TABLE_TOOL_COLS"]').not(':checked').length) : false);
                    form.render('checkbox', 'LAY_TABLE_TOOL_COLS_FORM');
                });

            }


        },
        funOperation: function (ReceiveOption) {
            var option = {
                type: null,
                url: null,
                confirmText: "确定执行吗?",
                resultConfirmText: "操作成功!",
                postdata: null,
                isPost: null,
                title: '标题',
                maxmin: true,
                btnId: 'btnSave',
                area: ['800px', '500px'],
                btn: ['保存', '取消'],
                onlyShow: false
            }
            //confirm只有确认按钮，用于执行更新等等ajax操作  
            //Open  用于添加修改等layer.open页面，点击确定后执行子页面隐藏的提交按钮
            //onlyShow=true 同上，区别在与没有保存功能，只能关闭
            option = $.extend({}, option, ReceiveOption);
            
            if (!!!option.type || !!!option.url) {
                return function (data) {};
            }

            if (option.type === "confirm") {
                return function (data) {
                    layer.confirm(option.confirmText, {
                        btn: ['确定', '取消']
                    }, function () {
                        var operation = layer.alert('正在执行中', {
                            icon: 16,
                            closeBtn: 0,
                            btn: 0,
                            title: false //不显示标题
                        });
                        var ajaxJson = {
                            type: "get",
                            url: option.url,
                            dataType: "json",
                            success: function (json) {
                                var thecf = layer.confirm(option.resultConfirmText + json.Msg, {
                                    btn: ['确定'] //按钮
                                        ,
                                    closeBtn: 0
                                }, function () {
                                    if (json.Correct > 0) {
                                        location.reload();
                                    } else {
                                        layer.close(thecf);
                                    }
                                });
                            },
                            error: function (data) {
                                layer.close(operation);
                                layer.msg("执行错误!");
                            },
                            complete: function (XMLHttpRequest, status) {
                                if (status == 'timeout') {
                                    layer.msg("超时", {
                                        icon: 5,
                                        time: 1000
                                    });
                                }
                            }

                        };

                        if (option.timeout) {
                            ajaxJson.timeout = option.timeout;
                        }

                        if (option.detail == 1) {
                            ajaxJson.success = function (json) {
                                var thecf = layer.confirm(option.resultConfirmText + ",成功" + json.Correct + "条,失败" + json.Error + "条!" + json.Msg, {
                                    btn: ['确定'] //按钮
                                        ,
                                    closeBtn: 0
                                }, function () {
                                    if (json.Correct > 0) {
                                        location.reload();
                                    } else {
                                        layer.close(thecf);
                                    }
                                });
                            }
                        }

                        if (option.isPost == 1) {
                            ajaxJson.type = "post";
                            ajaxJson.data = option.postdata;
                        }

                        $.ajax(ajaxJson);
                    }, function () {
                        layer.close();
                    });
                }
            } else if (option.type === "Open") {
                return function (data) {
                    var OpenOption = {
                        type: 2
                        
                    }


                    OpenOption.content = option.url;
                    
                        OpenOption.title = option.title;
                    
                   
                        OpenOption.maxmin = option.maxmin;
                    
                   
                       
                            OpenOption.area = option.area;
                        
                    
                    if (!!option.onlyShow) {
                        OpenOption.btn = ['关闭'];
                        OpenOption.yes = function (index, layero) {
                            layer.close(index);
                        }
                    } else {
                        
                            OpenOption.btn = option.btn;
                        
                        OpenOption.yes = function (index, layero) {
                            //点击确认触发 iframe 内容中的按钮提交
                            var submit = layero.find('iframe').contents().find("#" + option.btnId + "");
                            submit.click();
                        }
                        OpenOption.btn2 = function (index, layero) {
                                layer.close(index);
                        }

                    }
                    var pop = layer.open(OpenOption);
                    //parent.layer.closeAll();  子页面里执行关闭.
                    
                }
            }



            return function (data) {};
        },
        funTopOperation: function (ReceiveOption) {
            //1.top页面需引入layer 2.url为从top页面开始的相对路径
            var option = {
                type: null,
                url: null,
                confirmText: "确定执行吗?",
                resultConfirmText: "操作成功!",
                postdata: null,
                isPost: null,
                title: '标题',
                maxmin: true,
                btnId: 'btnSave',
                area: ['800px', '500px'],
                btn: ['保存', '取消'],
                onlyShow: false,
                top: true,
                zIndex: null,
                closeBtn:1
            }
            //confirm只有确认按钮，用于执行更新等等ajax操作  
            //Open  用于添加修改等layer.open页面，点击确定后执行子页面隐藏的提交按钮
            //onlyShow=true 同上，区别在与没有保存功能，只能关闭
            option = $.extend({}, option, ReceiveOption);

            if (!!!option.type || !!!option.url) {
                return function (data) { };
            }

            if (option.type === "confirm") {
                return function (data) {
                    layer.confirm(option.confirmText, {
                        btn: ['确定', '取消']
                    }, function () {
                        var operation = top.layer.alert('正在执行中', {
                            icon: 16,
                            closeBtn: 0,
                            btn: 0,
                            title: false //不显示标题
                        });
                        var ajaxJson = {
                            type: "get",
                            url: option.url,
                            dataType: "json",
                            success: function (json) {
                                var thecf = top.layer.confirm(option.resultConfirmText + json.Msg, {
                                    btn: ['确定'] //按钮
                                    ,
                                    closeBtn: 0
                                }, function () {
                                    if (json.Correct > 0) {
                                        $("#main", top.document).contents().find("#mywindows>table:not([style*=none]) iframe:eq(0)").attr('src', $("#main", top.document).contents().find("#mywindows>table:not([style*=none]) iframe:eq(0)").attr('src'));
                                    } else {
                                        top.layer.close(thecf);
                                    }
                                });
                            },
                            error: function (data) {
                                top.layer.close(operation);
                                top.layer.msg("执行错误!");
                            },
                            complete: function (XMLHttpRequest, status) {
                                if (status == 'timeout') {
                                    top.layer.msg("超时", {
                                        icon: 5,
                                        time: 1000
                                    });
                                }
                            }

                        };

                        if (option.timeout) {
                            ajaxJson.timeout = option.timeout;
                        }

                        if (option.detail == 1) {
                            ajaxJson.success = function (json) {
                                var thecf = top.layer.confirm(option.resultConfirmText + ",成功" + json.Correct + "条,失败" + json.Error + "条!" + json.Msg, {
                                    btn: ['确定'] //按钮
                                    ,
                                    closeBtn: 0
                                }, function () {
                                    if (json.Correct > 0) {
                                        $("#main", top.document).contents().find("#mywindows>table:not([style*=none]) iframe").attr('src', $("#main", top.document).contents().find("#mywindows>table:not([style*=none]) iframe").attr('src'));
                                    } else {
                                        top.layer.close(thecf);
                                    }
                                });
                            }
                        }

                        if (option.isPost == 1) {
                            ajaxJson.type = "post";
                            ajaxJson.data = option.postdata;
                        }

                        $.ajax(ajaxJson);
                    }, function () {
                        top.layer.close();
                    });
                }
            } else if (option.type === "Open") {
                return function (data) {
                    var OpenOption = {
                        type: 2

                    }


                    OpenOption.content = option.url;

                    OpenOption.title = option.title;


                    OpenOption.maxmin = option.maxmin;
                    if (!!option.zIndex &&( typeof option.zIndex =="number")) {
                        OpenOption.zIndex = option.zIndex;
                    }

                    OpenOption.area = option.area;

                   

                    if (!!option.onlyShow) {
                        if (option.closeBtn == 1) {
                            OpenOption.btn = ['关闭'];
                            OpenOption.yes = function (index, layero) {
                                top.layer.close(index);
                            }
                        } else {
                            
                        }
                    } else {
                        OpenOption.btn = option.btn;
                        OpenOption.yes = function (index, layero) {
                            //点击确认触发 iframe 内容中的按钮提交
                            var submit = layero.find('iframe').contents().find("#" + option.btnId + "");
                            submit.click();
                        }
                        OpenOption.btn2 = function (index, layero) {
                            top.layer.close(index);
                        }

                    }
                    var pop = top.layer.open(OpenOption);
                    //parent.layer.closeAll();  子页面里执行关闭.

                }
            }



            return function (data) { };
        },
        funSwitch: function () {
            var switchList = obj.option.switchList;
            var switchName = "";
            form.on('switch()', function (eventObj) {
                switchName = eventObj.elem.attributes.tempname.value;
                if (switchName) {
                    for (var i = 0; i < switchList.length; i++) {
                        if (switchList[i].special) {
                            if (switchList[i].special == "1") {
                                continue;
                            }
                        } else if (switchList[i].name == switchName) {
                            (function (eventObj) {
                                var id = eventObj.elem.attributes.tempid.value;
                                var msgTime = 1000;
                                var ajaxJson = {
                                    url: null,
                                    type: "get",
                                    dataType: "json",
                                    beforeSend: function () {
                                        eventObj.elem.disabled = true;
                                    },
                                    success: function (data) {
                                        if (data.num == "0") {
                                            layer.msg(data.value, {
                                                icon: 5,
                                                time: msgTime
                                            });
                                        } else {
                                            layer.msg(data.value, {
                                                icon: 6,
                                                time: msgTime
                                            });

                                        }
                                    },
                                    error: function (data) {
                                        layer.msg("执行错误!");
                                    },
                                    complete: function (XMLHttpRequest, status) {
                                        eventObj.elem.disabled = false;
                                        if (status == 'timeout') {
                                            layer.msg("超时", {
                                                icon: 5,
                                                time: msgTime
                                            });
                                        }
                                    }

                                };


                                ajaxJson.url = switchList[i].url + id;
                                ajaxJson.type = (switchList[i].type == "post" || switchList[i].type == "POST") ? "post" : "get";
                                if (switchList[i].timeout) {
                                    ajaxJson.timeout = switchList[i].timeout;
                                }
                                if (switchList[i].msgTime) {
                                    msgTime = switchList[i].msgTime;
                                }

                                $.ajax(ajaxJson);
                            })(eventObj);
                        }

                    }
                }

            });

        },
        funSearch: function (ReceiveOption) {
            var option = {
                searchData:null,
                callback: null,
                btnSearch:'btnSearch'
            }
            if (!!ReceiveOption) {
                option = $.extend({}, option, ReceiveOption);
            }
            //监听搜索
            form.on('submit(' + option.btnSearch + ')', function (data) {
                var field = data.field;

                if (obj.option.pageType == "TreeList") {
                    field[obj.option.treePrimaryKey] = null; //点击搜索先清空左侧树点击结果
                    field['page'] = 1;
                }


                if (obj.option.useXmSelect) {
                    var targetids = obj.option.targetids;
                    var targetList = obj.option.targetList;

                    //部门职务，下拉树 因是由插件生成的 需在此处手动设置值,还可在此处对其格式化 array targetids   "1,2,3"
                    for (let i = 0; i < targetids.length; i++) {
                        //tree -> nodeType:'leaf'  与上面参数一起使用解决不能获取到父级节点值的问题
                        var realarr = "";
                        //子部门 职务
                        field[(targetids[i] + "Children")] = $("#" + targetids[i] + "Children").text();
                        targetList[i].getTreeValue().forEach(function (item, index) {
                            if (index > 0) {
                                realarr += ",";
                            }
                            realarr += item.value;
                        });
                        field[targetids[i]] = realarr; //数组需要转字符串，否则会传多次name:[1,2] -> name[]:1  name[]:2
                    }
                }
                option.searchData =  field;
                //执行重载
                table.reload(obj.option.tableId, {
                    where: field,
                    text: "没有查找到数据",
                    done: function (res) {
                        if (res.count == 0) {
                            //执行搜索后，不管是没有数据或者程序错误都执行该方法
                            document.documentElement.querySelectorAll(".layui-table-body .layui-none")[0].innerHTML = res.msg;
                        }
                        if (!!option.callback) {
                            option.callback(option.searchData);
                        }
                    }
                });
            });
        },
        clearOption: function () {
            obj.option = null;
            obj.option ={};
        },
        setter: function (option) {
            obj.option = $.extend({}, obj.option, option);
        },
        getter: function (option) {
            var reData = null;
            if (!!option) {
                if (typeof option === "string") {
                    if (obj.option[option]) {
                        reData = obj.option[option];
                    }
                } else if (option instanceof Array) {
                    reData = [];
                    for (let i = 0; i < option.length; i++) {
                        reData.push(obj.option[option[i]]);
                    }
                }
            }
            return reData;
        },
        elRenderXmSelect: function (ReceiveOption) {
            let option = {
                contain: 0,
                callback: null,
                type: 'tree',
                toolbar: true
            } 
            if (!!ReceiveOption) {
                option = $.extend({}, option, ReceiveOption);
            }
            

            let count = 0;
            let targetids = obj.option.targetids;
            let targetimethods = obj.option.targetimethods;
            let targetList = [];
            let targetData = {};
            let height = "auto";
            height = obj.option.Xmheight;
            for (let i = 0; i < targetimethods.length; i++) {
                targetData[targetimethods[i]] = null;
            }
            //取得select树的数据
            for (let te = 0; te < targetids.length; te++) {
                //配置部门复选select

                //发送ajax获取部门数据json:
                $.ajax({
                    url: "?Method=" + targetimethods[te],
                    type: "get",
                    dataType: 'json',
                    async: true, //异步
                    success: function (resut) {
                        //响应有先后
                        for (let num = 0; num < targetimethods.length; num++) {
                            if (resut.type === targetimethods[num]) {
                                
                                targetData[targetimethods[num]] = resut.data;
                                count++;
                            }

                        }
                        //两个数据都已取到
                        if (count == targetimethods.length) {
                            renderTree();
                            obj.option.targetids = targetids;
                            obj.option.targetimethods = targetimethods;
                            obj.option.targetList = targetList;
                            obj.option.targetData = targetData;
                            if (!!option.callback) {
                                option.callback();
                            }
                        }

                    }

                });

            }

            //渲染xm-select与设置toolbar
            function renderTree() {
                var demo;
                for (let num = 0; num < targetids.length; num++) {
                    
                    if (option.type == "tree") {
                        demo = xmSelect.render({
                            el: "#" + targetids[num],
                            delay: 500,
                            autoRow: false, //自动换行
                            filterable: true, //开启搜索
                            //paging: true,  //开启分页
                            //pageSize: 3,  //分页条数
                            tree: {
                                show: true,
                                showFolderIcon: true, //是否展示三角图标
                                showLine: true, //虚线
                                indent: 10, //间距
                                strict: false //父子模式

                                //nodeType:'leaf'

                            },
                            toolbar: {
                                show: true,
                                list: ['ALL', 'CLEAR'],

                            },
                            height: height,
                            data: targetData[targetimethods[num]]
                        });
                    } else if (option.type == "list") {
                        demo = xmSelect.render({
                            el: "#" + targetids[num],
                            delay: 500,
                            autoRow: false, //自动换行
                            toolbar: {
                                show: true,
                                list: ['ALL', 'CLEAR'],

                            },
                            height: height,
                            filterable: true,
                            data: targetData[targetimethods[num]]
                        });
                    }
                    





                    targetList.push(demo);
                    $("#" + targetids[num] + " input").attr('name', '' + targetids[num] + '').addClass("layui-input"); //为其设置name属性，重要


                }


                //在所有数据都取得后设置toolbar,list不设置
                if (targetList.length == targetimethods.length && option.type != "list") {
                    //在render后设置,可以解决targetList[enven]始终获取的是第一个option的问题
                    for (let enven = 0; enven < targetids.length; enven++) {
                        //单选/连选 BEGIN    若开启 需设置strict true
                        //var enjson = {
                        //    name: '单选',
                        //    method: function() {
                        //                        let name =  targetList[enven].options.toolbar.list[2].name;
                        //                        name = (name == "连选" ? "单选" : "连选");
                        //                        targetList[enven].options.toolbar.list[2].name = name;
                        //                        targetList[enven].options.tree.strict = targetList[enven].options.tree.strict ? false : true
                        //                        var rearr = targetList[enven].getTreeValue().map(function (item, index) {
                        //                            if (name == "单选") {//连选模式下取selected
                        //                                if (item.selected) {
                        //                                    return item;
                        //                                }
                        //                            } else {//单选模式下直接返回
                        //                                return item;
                        //                            }

                        //                        });

                        //                        console.log("rearr");
                        //                        console.log(rearr);
                        //                        targetList[enven].setValue(rearr);

                        //                        targetList[enven].update(targetList[enven].options);

                        //           }
                        //}
                        //targetList[enven].options.toolbar.list.push(enjson);
                        //单选/连选 END 

                        //初始是否选中
                        let firstname = '含子集';
                        let firsticon = 'layui-icon layui-icon-radio';
                        if (option.contain == 0 || option.contain == false) {
                            firstname = '不包含';
                            firsticon = 'layui-icon layui-icon-circle';
                            
                        }
                        
                        //包含子部门 BEGIN
                        var evenjson = {
                            name: firstname,
                            icon: firsticon,
                            method: function () {
                                let name = targetList[enven].options.toolbar.list[2].name;
                                name = (name == "不包含" ? "含子集" : "不包含");
                                targetList[enven].options.toolbar.list[2].name = name;
                                let icon = "";
                                icon = (name == "不包含" ? 'layui-icon layui-icon-circle' : 'layui-icon layui-icon-radio');
                                targetList[enven].options.toolbar.list[2].icon = icon;

                                var val = "1";
                                val = (name == "不包含" ? "0" : "1");
                                $("#" + targetids[enven] + "Children").text(val);

                                targetList[enven].update(targetList[enven].options);
                            }
                        }
                        targetList[enven].options.toolbar.list.push(evenjson);
                        //包含子部门 END
                    }


                }



            }

            

            
            
        }


    };

    //输出接口
    exports('list', obj);
});